﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using HCQ2UI_Helper;
using System.Web.Http.ModelBinding;
using System.Net;
using Newtonsoft.Json.Linq;
using HCQ2_Common;
using HCQ2_Model.WeiXinApiModel.Model;
using System.IO;
using HCQ2_Model;
using HCQ2_Common.WebSockets;
using System.Net.Http;
using HCQ2WebAPI_Logic.Model;
using HCQ2WebAPI_Logic.Filters;

namespace HCQ2WebAPI_Logic.BaseAPIController
{
    /// <summary>
    ///  描述：微信端控制器 父类
    ///  创建人：Joychen
    ///  创建时间：2017-04-27
    /// </summary>
    //[WeiXinApiAuthorizeFilter] //取消全局登录验证
    //[RequestLogFilter]
    [DExceptionFilter]
    //[MyEnableThrottling]
    public class BaseWeiXinApiLogic: ApiController
    {
        /// <summary>
        ///  获取模型验证错误信息
        /// </summary>
        /// <param name="ModelState"></param>
        /// <returns></returns>
        protected string getErrorMessage(ModelStateDictionary ModelState)
        {
            if (ModelState.IsValid)
                return string.Empty;
            string message = string.Empty;
            foreach(var s in ModelState.Values)
            {
                foreach(var p in s.Errors)
                {
                    message = p.ErrorMessage;
                    if (string.IsNullOrEmpty(message))
                        message = "传递参数异常错误消息："+p.Exception.Message.ToString();
                    return message;
                }
            }
            return string.Empty;
        }
        /// <summary>
        /// 获取操作上下文对象
        /// </summary>
        protected OperateContext operateContext
        {
            get { return OperateContext.Current; }
        }
        /// <summary>
        ///  请求上下文
        /// </summary>
        protected HttpRequest request
        {
            get { return HttpContext.Current.Request; }
        }
        /// <summary>
        ///  根据关卡代码获取：关卡对象
        /// </summary>
        /// <param name="cpCode"></param>
        /// <returns></returns>
        protected T_VRCustomPass getCustomPass(string cpCode)
        {
            if (string.IsNullOrEmpty(cpCode))
                return null;
            var query = operateContext.bllSession.T_VRCustomPass.Select(s => s.cp_code.Equals(cpCode))?.FirstOrDefault();
            if (query == null)
                return null;
            return query;
        }
        /// <summary>
        ///  根据课件代码获取：课件对象
        /// </summary>
        /// <param name="fileCode"></param>
        /// <returns></returns>
        protected T_DocumentInfo getDocumentInfo(string  fileCode)
        {
            if (string.IsNullOrEmpty(fileCode))
                return null;
            var query = operateContext.bllSession.T_DocumentInfo.Select(s => s.file_code.Equals(fileCode) && s.file_status==5)?.FirstOrDefault();
            if (query == null)
                return null;
            return query;
        }

        #region 2.0 + 根据微信小程序 临时登录凭证获取 ，调用腾讯接口获取正式用户信息
        /// <summary>
        ///  根据微信小程序 临时登录凭证获取 ，调用腾讯接口获取正式用户信息
        /// </summary>
        /// <param name="code">临时登录凭证</param>
        /// <returns></returns>   
        protected ChartUser GetWebChartInfo(ChartCode param,out string errmsg)
        {
            errmsg = string.Empty;
            try
            {
                string serviceAddress = "https://api.weixin.qq.com/sns/jscode2session?";
                //此处填写自己小程序的appid和secret
                if (string.IsNullOrEmpty(param.appid))
                {
                    errmsg = "appid必传项！";
                    return null;
                }
                var webChart = operateContext.bllSession.T_VRWebChartSet.FindSingle(s => s.appid.Equals(param.appid));
                if (webChart == null)
                {
                    errmsg = "根据传递的appid并未查询到配置的secret，请确认！";
                    return null;
                }
                serviceAddress += "appid=" + param.appid + "&secret=" + webChart.appsecret + "&js_code=" + param.code + "&grant_type=authorization_code";
                //string appid = operateContext.bllSession.T_ItemCode.FindSingle(s => s.item_code.Equals("webChartApplet"))?.item_note;
                //if (!string.IsNullOrEmpty(appid))
                //    serviceAddress += appid.Trim('&');
                //else
                //    serviceAddress += "appid=wxfe311c8226afb00a&secret=19e590a5cac07b37f66620ae3f066769";
                //serviceAddress += "&js_code="+ param.code + "&grant_type=authorization_code";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
                request.Method = "GET";
                request.ContentType = "textml;charset=UTF-8";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                string jsonData = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                JObject json = JObject.Parse(jsonData);
                if(json.Property("errcode")!=null)
                {
                    //发生错误了
                    int errcode = Helper.ToInt(json["errcode"]);
                    if (errcode != 0)
                        errmsg = Helper.ToString(json["errmsg"]);
                    if (!string.IsNullOrEmpty(errmsg))
                        return null;
                }
                //返回用户信息
                return new ChartUser
                {
                    openid = Helper.ToString(json["openid"]),
                    session_key = Helper.ToString(json["session_key"])
                };
            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
                return null;
            }
        }
        #endregion

        #region 2.1 + 根据微信 openid ,access_token 获取个人详细信息
        /// <summary>
        ///  根据微信 openid ,access_token 获取个人详细信息
        /// </summary>
        /// <param name="param"></param>
        /// <param name="errmsg"></param>
        /// <returns></returns>
        protected WebChartUser GetChartUserInfo(ChartUser param, out string errmsg)
        {
            errmsg = string.Empty;
            try
            {
                //此处填写自己小程序的appid和secret
                string serviceAddress = $"https://api.weixin.qq.com/cgi-bin/user/info?access_token={param.session_key}&openid={param.openid}&lang=zh_CN";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
                request.Method = "GET";
                request.ContentType = "textml;charset=UTF-8";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                string jsonData = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                JObject json = JObject.Parse(jsonData);
                if (json.Property("errcode") != null)
                {
                    int errcode = Helper.ToInt(json["errcode"]);
                    if (errcode != 0)
                        errmsg = Helper.ToString(json["errmsg"]);
                    if (!string.IsNullOrEmpty(errmsg))
                        return null;
                }
                //返回用户信息
                return new WebChartUser
                {
                    openid = param.openid,
                    nickname = Helper.ToString(json["nickname"]),
                    sex = Helper.ToInt(json["sex"]),
                    city = Helper.ToString(json["city"]),
                    country = Helper.ToString(json["country"]),
                    headimgurl = Helper.ToString(json["headimgurl"])
                };
            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
                return null;
            }
        }
        #endregion
    }
}
